using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Plan;

namespace WPF_MVVM_Test.Services
{
    public class SalesOrderService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string BASE_URL = "http://8.140.242.140:8888/api/Sales/GetSalesOrderList"; // 替换为你的实际API地址

        public SalesOrderService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
            _httpClient.DefaultRequestHeaders.Add("accept", "text/plain");

            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
            };
        }

        /// <summary>
        /// 获取销售订单列表 - 使用真实API
        /// </summary>
        /// <param name="salesCode">销售编号筛选</param>
        /// <param name="salesName">销售名称筛选</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>销售订单列表和分页信息</returns>
        public async Task<(List<SalesOrderModel> orders, int totalCount, int totalPage)> GetSalesOrdersAsync(
            string? salesCode = "",
            string? salesName = "",
            int pageIndex = 1,
            int pageSize = 10)
        {
            try
            {
                // 构建查询参数
                var queryParams = BuildQueryParameters(salesCode, salesName, pageIndex, pageSize);
                var requestUrl = $"{BASE_URL}?{queryParams}";

                System.Diagnostics.Debug.WriteLine($"🌐 请求URL: {requestUrl}");

                // 发送HTTP请求
                var response = await _httpClient.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"📦 API响应: {jsonContent}");

                    var apiResponse = JsonSerializer.Deserialize<SalesOrderApiResponse>(jsonContent, _jsonOptions);

                    if (apiResponse?.IsSuc == true && apiResponse.Data?.Data != null)
                    {
                        // 为每个项目添加序号
                        AssignIndexToOrders(apiResponse.Data.Data, (pageIndex - 1) * pageSize);

                        System.Diagnostics.Debug.WriteLine($"✅ 成功获取 {apiResponse.Data.Data.Count} 条记录，总计 {apiResponse.Data.TotalCount} 条");

                        return (
                            apiResponse.Data.Data,
                            apiResponse.Data.TotalCount,
                            apiResponse.Data.TotalPage
                        );
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"🚨 获取销售订单列表异常: {ex.Message}");

                // API调用失败时，返回测试数据作为备选
                System.Diagnostics.Debug.WriteLine("🔄 API调用失败，使用测试数据");
                return GetTestData(salesCode, pageIndex, pageSize);
            }
        }

        /// <summary>
        /// 构建查询参数字符串
        /// </summary>
        private string BuildQueryParameters(string? salesCode, string? salesName, int pageIndex, int pageSize)
        {
            var queryParams = new List<string>();

            // 只有非空值才添加到查询参数中
            if (!string.IsNullOrWhiteSpace(salesCode))
            {
                queryParams.Add($"SalesCode={Uri.EscapeDataString(salesCode)}");
                System.Diagnostics.Debug.WriteLine($"🔍 添加销售编号搜索: {salesCode}");
            }

            if (!string.IsNullOrWhiteSpace(salesName))
            {
                queryParams.Add($"SalesName={Uri.EscapeDataString(salesName)}");
                System.Diagnostics.Debug.WriteLine($"🔍 添加销售名称搜索: {salesName}");
            }

            // 分页参数（必需）
            queryParams.Add($"PageIndex={pageIndex}");
            queryParams.Add($"PageSize={pageSize}");

            var result = string.Join("&", queryParams);
            System.Diagnostics.Debug.WriteLine($"🌐 完整查询参数: {result}");

            return result;
        }

        /// <summary>
        /// 为订单列表分配序号
        /// </summary>
        private void AssignIndexToOrders(List<SalesOrderModel> orders, int skipCount)
        {
            for (int i = 0; i < orders.Count; i++)
            {
                orders[i].Index = skipCount + i + 1;

                System.Diagnostics.Debug.WriteLine($"📊 订单 {orders[i].Index}: " +
                    $"编号={orders[i].SalesCode}, " +
                    $"名称={orders[i].SalesName}, " +
                    $"客户={orders[i].CustomerName}");
            }
        }

        /// <summary>
        /// 获取测试数据 - 作为API失败时的备选方案
        /// </summary>
        private (List<SalesOrderModel> orders, int totalCount, int totalPage) GetTestData(
            string? searchKeyword, int pageIndex, int pageSize)
        {
            var testData = new List<SalesOrderModel>
            {
                new SalesOrderModel { Id = "5225b0e3-a860-4e84-801c-03e846dd929d", SalesCode = "XS0003", SalesName = "锤子", Salesperson = "张三", CustomerName = "李四", Remarks = "锤子" },
                new SalesOrderModel { Id = "63881404-908c-45ff-80b2-b4df54859610", SalesCode = "XS0001", SalesName = "螺丝钉", Salesperson = "张三", CustomerName = "李四", Remarks = "螺丝钉" },
                new SalesOrderModel { Id = "b7793389-5319-446f-b1ea-569a2f6d4c56", SalesCode = "XS0002", SalesName = "木头", Salesperson = "张三", CustomerName = "李四", Remarks = "木头" },
                new SalesOrderModel { Id = "ebe1d1c8-91a7-40b4-bdd2-f6f25e859db2", SalesCode = "XS0004", SalesName = "钻头", Salesperson = "李七", CustomerName = "孙八", Remarks = "钻头套装" },
                new SalesOrderModel { Id = "test-id-003", SalesCode = "XS0005", SalesName = "螺丝刀", Salesperson = "张三", CustomerName = "李四", Remarks = "螺丝刀套装" },
                new SalesOrderModel { Id = "test-id-004", SalesCode = "XS0006", SalesName = "电钻", Salesperson = "王五", CustomerName = "赵六", Remarks = "电动工具" }
            };

            // 搜索过滤
            if (!string.IsNullOrEmpty(searchKeyword))
            {
                testData = testData.Where(o =>
                    o.SalesCode.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase) ||
                    o.SalesName.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase) ||
                    o.CustomerName.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase) ||
                    o.Salesperson.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            // 分页
            var totalCount = testData.Count;
            var totalPage = (int)Math.Ceiling((double)totalCount / pageSize);
            var pagedData = testData.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 添加序号
            for (int i = 0; i < pagedData.Count; i++)
            {
                pagedData[i].Index = (pageIndex - 1) * pageSize + i + 1;
            }

            return (pagedData, totalCount, totalPage);
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}

